package com.shjn.squirrel.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.GetImageReq;
import com.shjn.squirrel.bean.httpBean.RespCommonResult;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.utils.OkhttpHelper;
import com.shjn.squirrel.utils.SoundPlayUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 待机页轮播图
 */
public class AdvFragment extends BaseFragment {

    private static AdvFragment instance;
    private Banner mBanner;
    private ArrayList<Object> mImages;

    public AdvFragment() {
    }

    public synchronized static AdvFragment getInstance() {
        if (instance == null) {
            instance = new AdvFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.advertisement, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        //初始化轮播图控件
        mBanner = (Banner) mView.findViewById(R.id.banner);
        mBanner.setDelayTime(60000);
        mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        mImages = new ArrayList();
        //默认轮播图
        mImages.add(R.drawable.await1);
        mImages.add(R.drawable.await2);
        //设置图片集合
        mBanner.setImages(mImages);
        //设置图片加载器
        mBanner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                //Glide 加载图片简单用法
                Glide.with(context).load(path).
                        skipMemoryCache(true).
                        diskCacheStrategy(DiskCacheStrategy.NONE).
                        placeholder(R.drawable.await1).into(imageView);
            }
        });
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                //加载首页
                SoundPlayUtils.play(10);//播放欢迎使用语音
                mActivity.getFragmentManager().beginTransaction()
                        .replace(R.id.boot, BackgroundFragment.getInstance())
                        .replace(R.id.top, TopFragment.getInstance().setRecyclerPortalState(true))
                        .replace(R.id.mid, UserSelectFragment.getInstance())
                        .replace(R.id.bottom, BottomFragment.getInstance())
                        .commit();
            }
        });
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();

        //-----------测试使用----------//
        //如果出厂设置了，从服务器获取待机页轮播图(Constant.baseUrl + "machine/home/images")
//        if (!LocalStorage.getDeviceID(MyApplication.getInstance()).isEmpty()) {
//            OkhttpHelper.postRequest(Constant.myBaseUrl + "squirrelWebDemo/pictureServlet",
//                    new Gson().toJson(new GetImageReq(LocalStorage.getDeviceID(MyApplication.getInstance()), 0)),
//                    new Callback() {
//                        @Override
//                        public void onFailure(Call call, IOException e) {
//                            Log.i("info", "awaitImages_onFailure: " + e.getMessage());
//                        }
//
//                        @Override
//                        public void onResponse(Call call, Response response) {
//                            try {
//                                RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
//                                if (result.getStateCode() == 1) {
//                                    ArrayList<String> pictures = (ArrayList<String>) result.getResult().get("picture");
//                                    mImages = new ArrayList();
//                                    for (String pictureUrl : pictures) {
//                                        mImages.add(pictureUrl);
//                                    }
//                                    //更新轮播图
//                                    mActivity.runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            if (mBanner != null && AdvFragment.getInstance().isAdded()) {
//                                                mBanner.update(mImages);
//                                            }
//                                        }
//                                    });
//                                }
//                            } catch (IOException e) {
//                                Log.i("info", "awaitImages_onFailure: " + e.getMessage());
//                            }
//                        }
//                    });
//        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mBanner != null) {
            mBanner.releaseBanner();
            mBanner = null;
        }
        if (mImages != null) {
            mImages.clear();
            mImages = null;
        }
    }

}
